# 给定一棵二叉树，你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 
# 
#  
# 
#  示例 : 
# 给定二叉树 
# 
#            1
#          / \
#         2   3
#        / \     
#       4   5    
#  
# 
#  返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 
# 
#  
# 
#  注意：两结点之间的路径长度是以它们之间边的数目表示。 
#  Related Topics 树 深度优先搜索 二叉树 
#  👍 785 👎 0


from typing import List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.pass_node = 1

        def depth(node: TreeNode):
            if node is None:
                return 0
            left = depth(node.left)
            right = depth(node.right)
            self.pass_node = max(self.pass_node, left + right + 1)
            return max(left, right) + 1

        depth(root)
        return self.pass_node - 1




# leetcode submit region end(Prohibit modification and deletion)


def log(*args, **kwargs):
    print(*args, **kwargs)


# 结点为起点的最大路径: 左深度 + 右深度 + 1
#   推导:
#       路径长度: 路过的节点数-1
#       直径: 路过节点最大值 - 1
#       路径: 某一节点, 左右路径拼接得到
#       路过最多节点 -> 以某节点为根的深度

#     def diameterOfBinaryTree(self, root: TreeNode) -> int:
#         self.ans = 1
#
#         def depth(node: TreeNode) -> int:
#             if node is None:
#                 return 0
#             left = depth(node.left)
#             right = depth(node.right)
#             self.ans = max(self.ans, left + right + 1)
#             return max(left, right) + 1
#
#         depth(root)
#         return self.ans - 1
if __name__ == '__main__':
    #            1
    #          / \
    #         2   3
    #        / \
    #       4   5
    s = Solution()
    t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
    result = s.diameterOfBinaryTree(t)
    assert result == 3, result
